from django.contrib.auth.hashers import make_password
from rest_framework import serializers

from users.models import User
from system.serializers.role import RoleSerializers

# class UserSerializer(serializers.Serializer):
#     """用户信息序列化器"""
#     id = serializers.IntegerField()
#     username = serializers.CharField()
#     tel = serializers.CharField()
#     gender = serializers.CharField(source='get_gender_display')
#     email = serializers.EmailField()
#     introduction = serializers.CharField
#     permissions = serializers.SerializerMethodField()
#
#     def get_permissions(self, obj):
#         return obj._get_user_permissions()
class UserInfoSerializer(serializers.ModelSerializer):
    gender = serializers.CharField(source='get_gender_display')
    permissions = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id', 'username', 'tel', 'gender', 'email', 'introduction', 'permissions']

    def get_permissions(self, obj):
        return obj._get_user_permissions()


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    # username = serializers.CharField()
    # password = serializers.CharField(write_only=True)
    education = serializers.CharField(source='get_education_display', read_only=True)
    role = RoleSerializers(many=True, read_only=True)
    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'tel', 'email', 'education', 'is_active', 'role']
        extra_kwargs = {
            'username': {
                'required': True,
            },
            'password': {
                'write_only': True,
                'required': True,
            },
        }

    def save(self, **kwargs):
        self.validated_data['password'] = make_password(self.validated_data.get('password'))
        instance = super().save()

        return instance